<?php

namespace app\api\service;

use think\Controller;
use think\Db;
use Des3\DES3;
use think\Exception;

class Order extends Controller {

    /**
     * 获取用户订单列表
     * @param $param
     * @return array
     */
    public static function get_order_list($param) {
        try {
            $where = [];

            if (isset($param['status'])) {
                $where['status'] = $param['status'];
                if ($param['status'] == 6) {
                    $where['comment_status'] = 0;
                    $where['after_sale_status'] = ['in', '0, 2'];
                }
            }
            if (isset($param['comment_status'])) {
                $where['comment_status'] = $param['comment_status'];
            }

            if (isset($param['member_id'])) {
                $where['member_id'] = $param['member_id'];
            }

            if (isset($param['pattern_master_id'])) {
                $where['pattern_master_id'] = $param['pattern_master_id'];
            }

            if (!$where) {
                throw new \Exception('参数错误！！');
            }

            $data = model('order')->where($where)->order('id desc')->paginate(5);

            foreach ($data as $k => $v) {
                $data[$k]->orderProduct->product->brand->logo = get_img_url($v->orderProduct->product->brand->logo);
                $data[$k]->orderProduct->thumb = get_img_url($v->orderProduct->thumb);
            }
            return api_return(200, $data);
        } catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 获取预约量体页面数据
     * @param $param
     * @return string
     */
    public static function booking_quantity_body($param) {
        try {
            // + ------- 收货地址信息  -------- + //
            $address_id = $param['address_id'];
            if ($address_id > 0) {
                $address = Address::get_address_info(['id' => $address_id, 'member_id' => $param['member_id']]);
            } else {
                $address = Address::get_default_address_info(['member_id' => $param['member_id']]);
            }
            $data['address'] = $address['data'];

            // + ------- 产品信息  -------- + //
            $product = model('product')->get(['id' => $param['id']]);
            $data['product'] = $product;
            $data['product']['thumb'] = get_img_url($data['product']['thumb']);

            // + ------- 产品品牌信息  -------- + //
            $data['article'] = $product->brand;
            $data['article']['logo'] = get_img_url($data['article']['logo']);

            // + ------- 产品属性  -------- + //
            if (isset($param['attr']) && $param['attr']) {
                $attr = explode(',', $param['attr']);
                $arrt_ids = [];
                $attr_val_ids = [];
                foreach ($attr as $k => $v) {
                    $a = explode('-', $v);
                    $arrt_ids[] = $a[0];
                    $attr_val_ids[] = $a[1];
                }
                $attr = model('Attribute')->where('id', 'in', $arrt_ids)->select();
                $attr_value = model('AttrValue')->where('id', 'in', $attr_val_ids)->select();
                foreach ($attr as $key => $val) {
                    $attr_v = [];
                    foreach ($attr_value as $k => $v) {
                        if ($v['attribute_id'] == $val['id']) {
                            $attr_v[] = $v;
                        }
                    }
                    if ($attr_v) {
                        $val['value'] = $attr_v;
                    }
                    $attr[$key] = $val;
                }
                $data['attr'] = $attr;
            }

            // + ------- 订单信息  -------- + //
            $data['order'] = [
                'order_sn' => 'LT' . date('YmdHis') . rand(1000, 9999),
                'price' => $product->price
            ];

            return api_return(200, $data);
        }catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 创建订单
     * @param $param
     * @return array
     */
    public static function create_order($param) {
        Db::startTrans();
        try {
            // 根据订单类型获取数据
            if ($param['model'] == 'order') {
                $data = self::booking_quantity_body($param);
            }

            if (isset($data) && $data['code'] != 200) {
                throw new \Exception($data['msg']);
            }
            $data = $data['data'];

            //根据地址获取经纬度
            $lng_lat = \Map\Map::getLngLat($data['address']['r_province'] . $data['address']['r_city'] . $data['address']['r_area'] . $data['address']['address']);

            // 获取下单用户信息
            $member = model('member')->get(['id' => $param['member_id']]);

            // 组装订单数据
            $order_data = [
                'order_sn' => $param['order_sn'],
                'member_id' => $param['member_id'],
                'price' => $data['order']['price'],
                'consignee' => $data['address']['linkman'],
                'mobile' => $data['address']['mobile'],
                'province' => $data['address']['r_province'],
                'city' => $data['address']['r_city'],
                'area' => $data['address']['r_area'],
                'address' => $data['address']['address'],
                'lat' => $lng_lat['result']['location']['lat'],
                'lng' => $lng_lat['result']['location']['lng'],
                'pattern_master_id' => $member->relevance_pattern_master_id,
            ];

            $model_order = model($param['model']);
            $model_order->save($order_data);

            if ($param['model'] == 'order') {
                //组装订单产品数据
                $order_product_data = [
                    'order_id' => $model_order->id,
                    'product_id' => $param['id'],
                    'name' => $data['product']['name'],
                    'price' => $data['product']['price'],
                    'thumb' => $data['product']['thumb'],
                    'num' => 1,
                    'attr' => isset($data['attr']) && $data['attr'] ? json_encode($data['attr']) : ''
                ];
                model('order_product')->save($order_product_data);
            }

            Db::commit();

            /* +  -----    订单生成成功，发送短信通知  ----- + */
            //$manage_mobile = 18684937979;
            $manage_mobile = 15802571830;
            //$manage_mobile = 18670319761;
            $address = $order_data['province'] . $order_data['city'] . $order_data['area'] . $order_data['address'];
            $param = [
                'mobile' => $manage_mobile,
                'type' => 2,
                'order_sn' => $order_data['order_sn'],
                'address' => $address,
                'linkman' => $data['address']['linkman'],
                'address_mobile' => $data['address']['mobile']
            ];
            \app\api\service\NoteCode::send_code($param);

            /* +  -----    订单生成成功，发送微信模板消息通知  ----- + */
            $member = model('member')->get(['username' => $manage_mobile]);
            if ($member && $member['openid']) {
                $param = [
                    'touser' => $member['openid'],
                    'template_id' => '-wjkS0vN_NOaiYY6biMRlySepDiPxzUu3TfcFb5FQnk',
                    'url' => '',
                    'data' => [
                        'first' => [ 'value' => '发现新订单', 'color' => '#173177'],
                        'keyword1' => [ 'value' => $order_data['order_sn'], 'color' => '#173177'],
                        'keyword2' => [ 'value' => date('Y-m-d H:i:s'), 'color' => '#173177'],
                        'remark' => [ 'value' => "请尽快处理 \n 订制人：" . $data['address']['linkman'] . " \n 联系电话：" . $data['address']['mobile'] . " \n 收货地址：" . $address, 'color' => '#173177'],
                    ]
                ];
                send_create_order_wechat_tmplmsg(json_encode($param));
            }
            return api_return(200, ['order_id' => $model_order->id]);
        }catch (\Exception $e) {
            Db::rollback();
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 获取订单详情
     * @param $param
     * @return array
     */
    public static function get_order_info($param) {
        try {
            $order = model('order')->get(['id' => $param['id']]);

            // 返回数据
            $data['headimgurl'] = get_img_url($order->orderMember->memberRoleInfo->headimgurl);
            $data['brand_name'] = $order->orderProduct->product->brand->name;
            $data['brand_logo'] = get_img_url($order->orderProduct->product->brand->logo);
            $data['lat'] = $order->lat;
            $data['lng'] = $order->lng;
            $data['product_name'] = $order->orderProduct->name;
            $data['product_thumb'] = $order->orderProduct->thumb;
            $data['product_num'] = $order->orderProduct->num;
            $data['product_price'] = $order->orderProduct->price;
            $data['price'] = $order->price;
            $data['consignee'] = $order->consignee;
            $data['mobile'] = $order->mobile;
            $data['province'] = $order->province;
            $data['city'] = $order->city;
            $data['area'] = $order->area;
            $data['address'] = $order->address;
            $data['order_sn'] = $order->order_sn;
            $data['status'] = $order->status;
            $data['id'] = $order->id;

            return api_return(200, $data);
        } catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 删除订单
     * @param $param
     * @return array
     */
    public static function delete_order($param) {
        try {
            $order = model('order')->get(['id' => $param['id'], 'member_id' => $param['member_id']]);
            if (!$order) {
                throw new \Exception('订单不存在');
            }
            if ($order->status != 1) {
                throw new \Exception('订单状态异常，只有未付款订单可以删除');
            }
            $rs = model('order')->destroy(['id' => $param['id'], 'member_id' => $param['member_id']]);
            if($rs != 1) {
                throw new \Exception('订单不存在');
            }
            return api_return(200, []);
        } catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 确认收货
     * @param $param
     * @return array
     */
    public static function confirm_receipt($param) {
        try {
            $order = model('order')->get(['id' => $param['id'], 'member_id' => $param['member_id']]);
            if (!$order) {
                throw new \Exception('订单不存在');
            }
            if ($order->status != 5 && $order->status != 99) {
                throw new \Exception('订单状态异常，只有待收货订单可以确认收货');
            }
            $rs = model('order')->save(['receipt_time' => time(), 'status' => 6], ['id' => $param['id'], 'member_id' => $param['member_id']]);
            if($rs != 1) {
                throw new \Exception('订单不存在');
            }
            return api_return(200, []);
        } catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 量体师接单
     * @param $param
     * @return array
     */
    public static function order_receiving($param) {
        try {
            $order = model('order')->get(['id' => $param['id']]);
            if ($order->status != 2 ) {
                throw new \Exception('订单状态错误');
            }
            if ($order->pattern_master_id != 0 ) {
                throw new \Exception('手慢了，订单已被接走');
            }

            // 用户关联量体师ID为空  则进行关联
            $member = model('member')->get(['id' => $order->member_id]);
            if ($member->relevance_pattern_master_id == 0) {
                model('member')->save(['relevance_pattern_master_id' => $param['pattern_master_id']],['id' => $order->member_id]);
            }

            // 更新订单数据
            $rs = model('order')->save(['status' => 3, 'pattern_master_id' => $param['pattern_master_id'], 'pattern_master_receive_time' => time()], ['id' => $param['id']]);
            if($rs != 1) {
                throw new \Exception('接单失败，请刷新重试');
            }
            return api_return(200, []);
        } catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 量体师确认量体完成
     * @param $param
     * @return array
     */
    public static function affirm_measure($param) {
        try {
            $order = model('order')->get(['id' => $param['id'], 'pattern_master_id' => $param['pattern_master_id']]);
            if (!$order) {
                throw new \Exception('订单不存在');
            }

            if ($order->status != 3 ) {
                throw new \Exception('订单状态错误');
            }

            // 更新订单数据
            $rs = model('order')->save(['status' => 4,  'pattern_master_affirm_time' => time()], ['id' => $param['id']]);
            if($rs != 1) {
                throw new \Exception('确认失败，请刷新重试');
            }
            return api_return(200, []);
        } catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 获取订单量体数据页面数据
     * @param $param
     * @return array
     */
    public static function figure_measure($param) {
        try {
            $order = model('order')->get(['id' => $param['id']]);
            $data = $order->orderFigureMeasure;
            return api_return(200, $data);
        } catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 保存訂單订单量体数据
     * @param $param
     * @return array
     */
    public static function save_figure_measure($param) {
        try {
            // 根据订单ID检查是否有量体数据
            $figure_measure = model('order_figure_measure_data')->get(['order_id' => $param['order_id']]);

            $figure_measure_data = [
                'stature' => $param['stature'],
                'weight' => $param['weight'],
                'size' => $param['size'],
                'head_size' => $param['head_size'],
                'neck_line' => $param['neck_line'],
                'front_cross' => $param['front_cross'],
                'back_across' => $param['back_across'],
                'shoulder' => $param['shoulder'],
                'outside_sleeve' => $param['outside_sleeve'],
                'muffs' => $param['muffs'],
                'sleeve_width' => $param['sleeve_width'],
                'chest_circumference' => $param['chest_circumference'],
                'waistline' => $param['waistline'],
                'hipline' => $param['hipline'],
                'hip_gear' => $param['hip_gear'],
                'calf_girth' => $param['calf_girth'],
                'leg_opening' => $param['leg_opening'],
                'outside_length' => $param['outside_length'],
                'tong_fork' => $param['tong_fork'],
                'after_the_length' => $param['after_the_length'],
                'habit' => $param['habit'],
                'image_1' => $param['image_1'],
                'image_2' => $param['image_2'],
                'image_3' => $param['image_3'],
            ];

            if ($figure_measure) {
                model('order_figure_measure_data')->save($figure_measure_data, ['id' => $figure_measure->id]);
            } else {
                $figure_measure_data['order_id'] = $param['order_id'];
                model('order_figure_measure_data')->save($figure_measure_data);
            }

            return api_return(200, []);
        } catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 申请售后页面数据
     * @param $param
     * @return array
     */
    public static function apply_aftermarket($param) {
        try {
            $data = model('order')->get(['id' => $param['order_id'], 'member_id' => $param['member_id']]);
            return api_return(200, $data);
        } catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 保存售后申请数据
     * @param $param
     * @return array
     */
    public static function save_apply_aftermarket($param) {
        Db::startTrans();
        try {
            $order_after_sale = model('order_after_sale')->get(['order_id' => $param['order_id'], 'status' => ['lt', 7]]);
            if ($order_after_sale) {
                throw new \Exception('不要重复申请');
            }

            // 获取微信数据
            $order = model('order')->get(['id' => $param['order_id']]);

            // 添加售后记录
            $aftermarket_data = [
                'aftermarket_sn' => 'SH' . date('YmdHis') . rand(1000, 9999),
                'member_id' => $param['member_id'],
                'msg' => $param['msg'],
                'linkman' => $param['linkman'],
                'mobile' => $param['mobile'],
                'order_id' => $param['order_id'],
                'order_status' => $order->status
            ];
            $model = model('order_after_sale');
            $model->save($aftermarket_data);

            // 保存售后图片
            $aftermarket_img_data = [];
            if (isset($param['image']) && is_array($param['image'])) {
                foreach ($param['image'] as $v) {
                    $aftermarket_img_data[] = [
                        'order_after_sale_id' => $model->id,
                        'image' => $v
                    ];
                }
                model('order_after_sale_img')->saveAll($aftermarket_img_data);
            }

            // 修改订单售后状态
            model('order')->save(['after_sale_status' => 1], ['id' => $param['order_id']]);

            Db::commit();
            return api_return(200, []);
        } catch (\Exception $e) {
            Db::rollback();
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 获取售后列表
     * @param $param
     * @return array
     */
    public static function get_order_after_sale_list($param) {
        try {
            $where['member_id'] = $param['member_id'];
            $model = model('order_after_sale');
            $member_registration_list = $model->where($where)->order('create_time desc')->paginate();
            $data = [];
            if ($member_registration_list) {
                foreach ($member_registration_list as $v) {
                    $data[] = [
                        'brand_logo' => get_img_url($v->order->orderProduct->product->brand->logo),
                        'brand_name' => $v->order->orderProduct->product->brand->name,
                        'product_name' => $v->order->orderProduct->name,
                        'product_thumb' => $v->order->orderProduct->thumb,
                        'product_price' => $v->order->orderProduct->price,
                        'product_num' => $v->order->orderProduct->num,
                        'status' => $v->status,
                        'price' => $v->price,
                        'status_text' => get_order_after_sale_status($v->status),
                        'order_sn' => $v->order->order_sn,
                        'id' => $v->id,
                    ];
                }
            }

            return api_return(200, $data);
        } catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 获取售后详情数据
     * @param $param
     * @return array
     */
    public static function get_order_after_sale_info($param) {
        try {
            $order_after_sale = model('order_after_sale')->get(['id' => $param['id'], 'member_id' => $param['member_id']]);

            $data = [
                'id' => $order_after_sale->id,
                'member_express_sn' => $order_after_sale->member_express_sn,
                'terrace_express_sn' => $order_after_sale->terrace_express_sn,
                'order_sn' => $order_after_sale->order->order_sn,
                'product_name' => $order_after_sale->order->orderProduct->name,
                'product_thumb' => $order_after_sale->order->orderProduct->thumb,
                'product_price' => $order_after_sale->order->orderProduct->price,
                'product_num' => $order_after_sale->order->orderProduct->num,
                'aftermarket_sn' => $order_after_sale->aftermarket_sn,
                'msg' => $order_after_sale->msg,
                'create_time' => $order_after_sale->create_time,
                'status' => $order_after_sale->status,
                'status_text' => get_order_after_sale_status($order_after_sale->status)
            ];

            // 图片
            $images = $order_after_sale->images;
            foreach ($images as $v) {
                $data['images'][] =  get_img_url($v->image);
            }
            return api_return(200, $data);
        } catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 保存用户发货信息
     * @param $param
     * @return array
     */
    public static function save_logistics($param) {
        try {
            model('order_after_sale')->save(['member_express_sn' => $param['member_express_sn'], 'status' => 4, 'member_deliver_goods_time' => time()], ['id' => $param['id'], 'member_id' => $param['member_id']]);
            return api_return(200, []);
        } catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 售后单用户确认完成
     * @param $param
     * @return array
     */
    public static function after_sale_confirm_receipt($param) {
        try {
            model('order_after_sale')->save(['status' => 7, 'member_affirm_time' => time()], ['id' => $param['id'], 'member_id' => $param['member_id']]);
            return api_return(200, []);
        } catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 订单分账
     * @param $order_id
     * @return array
     */
//    public static function sub_account($order_id){
//        try {
//            // 获取订单信息
//            $order = model('order')->get(['id' => $order_id]);
//            if (!$order) {
//                throw new \Exception('订单不存在');
//            }
//
//            if ($order->sub_account_status != 0) {
//                throw new \Exception('已分账');
//            }
//
//            //获取用户信息
//            $member_id = $order->member_id;
//            $f_list = $order->orderMember->parents;
//
//            $model_account_log = Model('account_log');
//            $model_user_level = Model('user_level');
//
//            //用户上级市场
//            $f_list = explode(',', $f_list);
//            if ($f_list) {  // 上级市场存在才处理
//                rsort($f_list);  // 根据值倒排
//                foreach ($f_list as $member_id) {
//                    //获取当前用户的基于这个订单所产生的总的收益
//                    $earnings = $model_account_log->getMemberEarningsByOrder($order_id, $member_id, 'order');
//                    if(!$earnings) {
//                        continue;
//                    }
//
//                    //首先获取用户数据，判断冻结金额是否大于收益金额
//                    $f_member_where = array(
//                        'member_id' => $member_id
//                    );
//                    $f_user = $model_member->getMemberInfo($f_member_where, 'member_id,available_predeposit, freeze_predeposit, p_level, person_pv, team_pv, offline_num');
//                    //if($f_user['freeze_predeposit'] >= $earnings) {
//                    //会员表可用余额增加相等数额，冻结金额减去相等数额
//                    $data = array(
//                        'available_predeposit' => $f_user['available_predeposit'] + $earnings,
//                        'freeze_predeposit' => $f_user['freeze_predeposit'] - $earnings
//                    );
//                    $model_member->where($f_member_where)->update($data);
//
//                    //account_log
//                    $data_log = array(
//                        'member_id' => $member_id,
//                        'order_id' => $order_id,
//                        'change_time' => TIMESTAMP,
//                        'change_type' => 'fz', //fz
//                        'frozen_money' => '-' . $earnings,
//                        'user_money' =>  $earnings,
//                        'change_desc' => '通过订单' . $order_info['order_sn'] . '分账可用余额：+ ' . $earnings . ',冻结金额: -' . $earnings,
//                        'money' => $data['available_predeposit'],
//                        'f_money' => $data['freeze_predeposit'],
//                        'admin' => $this->admin_info['name']
//                    );
//                    account_log($data_log);
//                    //account_log - end
//
//                    $this->log('订单' . $order_info['order_sn'] . '分账成功,可用余额：+ ' . $earnings . ',冻结金额: -' . $earnings,1);
//                    //}
//
//                    //计算当前用户是否可以升级
//                    if($f_user['p_level'] < 5) {
//                        //如果当前用户市场等级还没有到达顶级，就检查他是否满足升级条件
//                        //获取辅助市场业绩
//                        $second_where = array(
//                            'parent_id' => $member_id
//                        );
//                        $second_pv = $model_member->getMemberList($second_where, 'team_pv', 0, 'team_pv desc');
//                        $f_user['second_pv'] = $second_pv[1]['team_pv'] ? $second_pv[1]['team_pv'] : 0;//所有下级市场中第二大的就是辅助市场
//                        $model_user_level->showMemberIsUpgrade($f_user);
//                    }
//                }
//
//                //分账完成将订单改为已分账
//                $model_vr_order = Model('order');
//                $model_vr_order->editOrder(array('is_routing'=>2, 'order_state'=>50), array('order_id' => $order_id));
//
//                //返回页面
//                $url = array(
//                    array(
//                        'url'=>'index.php?act=vr_order&op=order_fz',
//                        'msg'=>'返回分账订单列表',
//                    )
//                );
//                showMessage('分账完成',$url);
//            }
//
//
//
//            return api_return(200, []);
//        } catch (\Exception $e) {
//            return api_return(0, [], $e->getMessage());
//        }
//    }
}